import logging

from flask import request, make_response, json

from .hal import ProblemSchema

log = logging.getLogger(__name__)


def make_hal_response(serialized, status=200):
    """200 OK
    Content-Type: application/hal+json
    """
    j = json.dumps(serialized)

    log.debug(j)

    response = make_response(j, status)
    response.headers['Content-Type'] = 'application/json'
    return response


def make_problem_response(error, headers=None):
    """5XX/4XX
    Content-Type: application/problem+json
    """
    problem = error or {}
    problem['instance'] = request.path
    serialized = hal.ProblemSchema.serialize(problem)
    j = json.dumps(serialized)

    log.debug(j)

    response = make_response(j, status)
    response.headers['Content-Type'] = 'application/json'
    if headers:
        for header, value in headers.items():
            response.headers[header] = value

    return response
